"""
主题: 作为客户端与HTTP服务交互
问题: 你需要通过HTTP协议以客户端的方式访问多种服务。例如，下载数据或者与基于REST的API进行交互。
提示 : 
"""
from urllib import request, parse
import requests

index_url = 'http://www.python.org/index.html'
post_url = 'http://httpbin.org/post'

def recipe1():
    '''简单的Get'''

    # Base URL being accessed
    url = 'http://httpbin.org/get'

    # Dictionary of query parameters (if any)
    parms = {
    'name1' : 'value1',
    'name2' : 'value2'
    }

    # Encode the query string
    querystring = parse.urlencode(parms)

    # Make a GET request and read the response
    u = request.urlopen(url+'?' + querystring)
    resp = u.read()
    print(f"{resp = }")

def recipe2():
    '''简单的Post'''

    # Base URL being accessed
    url = index_url

    # Dictionary of query parameters (if any)
    parms = {
    'name1' : 'value1',
    'name2' : 'value2'
    }

    # Encode the query string
    querystring = parse.urlencode(parms)

    # Make a POST request and read the response
    u = request.urlopen(url, querystring.encode('ascii'))
    resp = u.read()   
    print(f"{resp = }")

def recipe3():
    '''复杂的Post'''

    # Base URL being accessed
    url = index_url

    # Dictionary of query parameters (if any)
    parms = {
    'name1' : 'value1',
    'name2' : 'value2'
    }

    # Extra headers
    headers = {
        'User-agent' : 'none/ofyourbusiness',
        'Spam' : 'Eggs'
    }

    resp = requests.post(url, data=parms, headers=headers)

    # Decoded text returned by the request
    # 多种方式从请求中返回响应结果的内容
    print(f"{resp.text = }")
    print(f"{resp.content = }")
    print(f"{resp.json() = }")

def recipe4():
    '''提取出一些HTTP头数据的字段'''
    resp = requests.head(index_url)

    print(f"{resp.headers = }")

def recipe5():
    '''基本认证登录'''
    resp = requests.get('http://pypi.python.org/pypi?:action=login',
                        auth=('user','password'))
    print(f"{resp = }")

def recipe6():
    '''将HTTP cookies从一个请求传递到另一个的例子'''

    # First request
    resp1 = requests.get(index_url)

    # Second requests with cookies received on first requests
    resp2 = requests.get(index_url, cookies=resp1.cookies)
    print(f"{resp2 = }")

def recipe7():
    '''上传文件'''
    url = index_url
    files = { 'file': ('data.csv', open('../somefile.txt', 'rb')) }

    r = requests.post(url, files=files)
    print(f"{r.text = }")

def main():
    print('recipe1'.center(20, '*'))
    recipe1()
    print('recipe2'.center(20, '*'))
    recipe2()
    print('recipe3'.center(20, '*'))
    recipe3()
    print('recipe4'.center(20, '*'))
    recipe4()
    print('recipe5'.center(20, '*'))
    recipe5()
    print('recipe6'.center(20, '*'))
    recipe6()
    print('recipe7'.center(20, '*'))
    recipe7()

if __name__ == '__main__':
    main()   